package com.piece.admin.controller.system;

import com.piece.admin.model.TbSysJob;
import com.piece.admin.service.TbSysJobService;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.support.dto.UserDetailDTO;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.bootstrap.Valid;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.web.controller.FrameWorkController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags = {"调度任务管理"})
@RequestMapping("/api/system/job")
public class SysJobController extends FrameWorkController {

    @Resource
    private TbSysJobService tbSysJobService;

    @PostMapping("/list")
    @AclPermission(code = "tool:quartz:view")
    @ApiOperation(value = "查询调度任务列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = tbSysJobService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "tool:quartz:view")
    @ApiOperation(value = "查询调度任务分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = tbSysJobService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "tool:quartz:view")
    @ApiOperation(value = "生成调度任务")
    @ApiImplicitParam(name = "id", value = "任务ID")
    public AjaxResponse loadForm() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        TbSysJob job = new TbSysJob();
        if (id != 0) {
            job = tbSysJobService.findById(id);
        }
        return success(job);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "tool:quartz:add,tool:quartz:edit")
    @ApiOperation(value = "保存调度任务")
    @ApiImplicitParam(value="调度任务", dataTypeClass = TbSysJob.class, type = "body")
    public AjaxResponse save(UserDetailDTO userDetail) {
        TbSysJob job = new TbSysJob();
        try {
            initDB(job);
            job.setCreateBy(userDetail.getId());
            job.setCreateTime(new Date());
            tbSysJobService.insertOrUpdate(job);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "tool:quartz:delete")
    @ApiOperation(value = "删除调度任务")
    @ApiImplicitParam(name = "ids", value = "任务ID集合")
    public AjaxResponse delete() {
        try {
            String ids = getRequest().getParameter("ids");
            if (StringUtil.isNotEmpty(ids)) {
                tbSysJobService.delete(ids.split(FrameWorkConstants.SPLIT_PARAM));
            }
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.DELETE_FAILURE), e.getMessage());
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/changeStatus")
    @AclPermission(code = "tool:quartz:exec")
    @ApiOperation(value = "任务调度状态修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name="jobId", value = "任务ID"),
            @ApiImplicitParam(name="status", value = "任务状态，0完成 1删除 2执行中 3暂停 4错误")
    })
    public AjaxResponse changeStatus() {
        long jobId = Convert.toLong(getRequest().getParameter("jobId"), 0L);
        String status = getRequest().getParameter("status");
        TbSysJob job = tbSysJobService.findById(jobId);
        if (null != job) {
            job.setStatus(status);
            tbSysJobService.changeStatus(job);
        }
        return success();
    }

    @SubmitPermission
    @PostMapping("/run/{id}")
    @AclPermission(code = "tool:quartz:exec")
    @ApiOperation(value = "立即执行一次任务")
    @ApiImplicitParam(name="id", value = "任务ID", type = "path")
    public AjaxResponse run(@PathVariable long id) {
        TbSysJob job = tbSysJobService.findById(id);
        if (null != job) {
            tbSysJobService.run(job);
        }
        return success();
    }

    @GetMapping("/checkJobName")
    @ApiOperation(value = "校验JobName是否唯一")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobId", value = "任务ID"),
            @ApiImplicitParam(name = "jobName", value = "任务名称")
    })
    public Valid checkJobName() {
        String jobId = getRequest().getParameter("jobId");
        String jobName = getRequest().getParameter("jobName");
        boolean result = tbSysJobService.checkJobNameUniq(Convert.toLong(jobId, null), jobName);
        Valid valid = new Valid(result);
        return valid;
    }

    @GetMapping("/checkJobGroup")
    @ApiOperation(value = "校验JobGroup是否唯一")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobId", value = "任务ID"),
            @ApiImplicitParam(name = "jobGroup", value = "任务组")
    })
    public Valid checkJobGroup() {
        String jobId = getRequest().getParameter("jobId");
        String jobGroup = getRequest().getParameter("jobGroup");
        boolean result = tbSysJobService.checkJobGroupUniq(Convert.toLong(jobId, null), jobGroup);
        Valid valid = new Valid(result);
        return valid;
    }

    @GetMapping("/checkCronExpression")
    @ApiOperation(value = "校验cron表达式是否有效")
    @ApiImplicitParam(name = "cronExpression", value = "表达式")
    public Valid checkCronExpression() {
        String cronExpression = getRequest().getParameter("cronExpression");
        boolean result = tbSysJobService.checkCronExpression(cronExpression);
        Valid valid = new Valid(result);
        return valid;
    }
}
